package com.win.all.service.impl;

import com.win.all.service.IDeadLockService;

/**
 * 死锁代码实例【仅仅是示例】
 */
public class DeadLockServiceImpl implements IDeadLockService, Runnable {

    private String lockOrder;

    @Override
    public void setLockOrder(String t) {
        lockOrder = t;
    }

    private static final Object A = new Object();
    private static final Object B = new Object();

    @Override
    public void run() {
        if ("LockAB".equals(lockOrder)) {
            this.lockAB();
        } else if ("LockBA".equals(lockOrder)) {
            this.lockBA();
        }
    }

    @Override
    public void lockAB() {
        String threadId = "ThreadId:" + Thread.currentThread().getId();
        System.out.println(threadId + "[try lock a]");
        synchronized (A) {
            System.out.println(threadId + "[locked a]");
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
            }
            System.out.println(threadId + "[try lock b]");
            synchronized (B) {
                System.out.println(threadId + "locked b--【这里永远执行不到，代表死锁了】");
            }
        }
        System.out.println(threadId + "[lockAB end]");
    }

    @Override
    public void lockBA() {
        String threadId = "ThreadId:" + Thread.currentThread().getId();
        System.out.println(threadId + "[try lock b]");
        synchronized (B) {
            System.out.println(threadId + "[locked b]");
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
            }
            System.out.println(threadId + "[try lock a]");
            synchronized (A) {
                System.out.println(threadId + "locked a--【这里永远执行不到，代表死锁了】");
            }
        }
        System.out.println(threadId + "[lockBA end]");
    }
}
